package com.jishuo.base.config;

import com.hazelcast.config.Config;
import com.hazelcast.config.JoinConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;

@Configuration
public class HazelcastConfig {

    @Value("${hazelcast.instance-name}")
    private String instanceName;

    @Value("${hazelcast.network.port}")
    private int port;

    @Value("${hazelcast.network.join.multicast.enabled}")
    private boolean multicastEnabled;

    @Value("${hazelcast.network.join.tcp-ip.enabled}")
    private boolean tcpIpEnabled;

    @Value("${hazelcast.network.join.tcp-ip.members}")
    private String tcpIpMembers;

    @Bean
    public Config myHazelcastConfig() {
        Config config = new Config();
        config.setInstanceName(instanceName);
        
        NetworkConfig networkConfig = config.getNetworkConfig();
        networkConfig.setPort(port);

        JoinConfig joinConfig = networkConfig.getJoin();
        joinConfig.getMulticastConfig().setEnabled(multicastEnabled);
        
        joinConfig.getTcpIpConfig().setEnabled(tcpIpEnabled);
        if (tcpIpEnabled) {
            joinConfig.getTcpIpConfig().setMembers(Collections.singletonList(tcpIpMembers));
        }

        return config;
    }

    @Bean
    public HazelcastInstance hazelcastInstance() {
        return Hazelcast.newHazelcastInstance(myHazelcastConfig());
    }
}
